package com.feng.gaoerfu.view.locktableview;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.feng.gaoerfu.R;
import com.feng.gaoerfu.adapter.TableAdapter;
import com.feng.gaoerfu.bean.BallPersonData;
import com.feng.gaoerfu.bean.TableData;
import com.feng.gaoerfu.bean.TitleData;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明 可锁定首行和首列的表格视图
 * 作者 郭翰林
 * 创建时间 2017/3/29.
 */

public class LockTableView {
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 表格父视图
     */
    private ViewGroup mContentView;

    /**
     * 表格视图
     */
    private View mTableView;
    /**
     * 是否锁定首行
     */
    private boolean isLockFristRow = true;
    /**
     * 是否锁定首列
     */
    private boolean isLockFristColumn = true;
    /**
     * 最大列宽(dp)
     */
    private int maxColumnWidth;
    /**
     * 最小列宽(dp)
     */
    private int minColumnWidth;
    /**
     * 最大行高(dp)
     */
    private int maxRowHeight;
    /**
     * 最小行高dp)
     */
    private int minRowHeight;
    /**
     * 第一行背景颜色
     */
    private int mFristRowBackGroudColor;
    /**
     * 数据为空时的缺省值
     */
    private String mNullableString;
    /**
     * 单元格字体大小
     */
    private int mTextViewSize;
    /**
     * 表格头部字体颜色
     */
    private int mTableHeadTextColor;
    /**
     * 表格内容字体颜色
     */
    private int mTableContentTextColor;
    /**
     * 表格监听事件
     */
    private OnTableViewListener mTableViewListener;

    private int tableWithAndHeight = 70;

    //表格数据

    public void setTableFristTitleData(ArrayList<TitleData> tableFristTitleData) {
        mTableFristTitleData = tableFristTitleData;
    }

    public void setTableFirstColumnDatas(ArrayList<BallPersonData> tableBallPersonDatas) {
        mTableBallPersonDatas = tableBallPersonDatas;
    }

    public void setTableRowDatas(ArrayList<ArrayList<TableData>> tableRowDatas) {
        mTableRowDatas = tableRowDatas;
    }

    /**
     * 表格第一行数据,不包括第一个元素
     */
    private ArrayList<TitleData> mTableFristTitleData = new ArrayList<>();
    /**
     * 表格第一列数据，不包括第一个元素
     */
    private ArrayList<BallPersonData> mTableBallPersonDatas = new ArrayList<>();
    /**
     * 表格左上角数据
     */
    private String mLeftTopTitle;
    /**
     * 表格每一行数据，不包括第一行和第一列
     */
    private ArrayList<ArrayList<TableData>> mTableRowDatas = new ArrayList();
    //表格数据


    /**
     * 记录每列最大宽度
     */
    private ArrayList<Integer> mColumnMaxWidths = new ArrayList<Integer>();
    /**
     * 记录每行最大高度
     */
    private ArrayList<Integer> mRowMaxHeights = new ArrayList<Integer>();
    /**
     * 把所有的滚动视图放图列表，后面实现联动效果
     */
    private ArrayList<HorizontalScrollView> mScrollViews = new ArrayList<HorizontalScrollView>();


    //表格视图
    /**
     * 表格左上角视图
     */
    private LinearLayout mLeftTopView;
    /**
     * 第一行布局（锁状态）
     */
    private LinearLayout mLockHeadView;

    /**
     * 第一行滚动视图（锁状态）
     */
    private CustomHorizontalScrollView mLockScrollView;

    /**
     * 表格主视图
     */
    private ScrollView mTableScrollView;
    private onClickItemListener mClickItemListener;
    private TableAdapter mTableAdapter;


    /**
     * 构造方法
     *
     * @param mContext     上下文
     * @param mContentView 表格父视图
     */
    public LockTableView(Context mContext, ViewGroup mContentView) {
        this.mContext = mContext;
        this.mContentView = mContentView;

        initAttrs();
    }

    /**
     * 初始化属性
     */
    private void initAttrs() {
        mTableView = LayoutInflater.from(mContext).inflate(R.layout.locktableview, null);
        maxColumnWidth = 100;
        minColumnWidth = 70;
        minRowHeight = 20;
        maxRowHeight = 70;
        mNullableString = "N/C";
        mTableHeadTextColor = R.color.beijin;
        mTableContentTextColor = R.color.border_color;
        mFristRowBackGroudColor = R.color.table_head;
        mTextViewSize = 16;
    }

    /**
     * 展现视图
     */
    public void show() {
        initData();
        initView();
        mContentView.removeAllViews();//清空视图
        mContentView.addView(mTableView);
    }
    /**
     * 展现视图
     */
    public void refresh() {
        mLockScrollView.removeAllViews();
        mContentView.removeAllViews();//清空视图
        mTableScrollView.removeAllViews();
        initData();
        initView();
        mContentView.addView(mTableView);
    }


    /**
     * 初始化表格数据
     */
    private void initData() {
        if (mTableRowDatas != null && mTableRowDatas.size() > 0) {
            //构造第一列数据,并且构造表格每行数据
            Log.d("第一行数据", mTableFristTitleData.toString());
            Log.d("第一列数据", mTableBallPersonDatas.toString());
            Log.d("每行数据", mTableRowDatas.toString());
        } else {
            Toast.makeText(mContext, "表格数据为空！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 初始化表格视图
     */
    private void initView() {
        mLeftTopView = (LinearLayout) mTableView.findViewById(R.id.lockHeadView_left_top);
        mLockHeadView = (LinearLayout) mTableView.findViewById(R.id.lockHeadView);
        mLockScrollView = (CustomHorizontalScrollView) mTableView.findViewById(R.id.lockHeadView_ScrollView);
        mTableScrollView = (ScrollView) mTableView.findViewById(R.id.table_scrollView);
        mLockHeadView.setBackgroundColor(ContextCompat.getColor(mContext, mFristRowBackGroudColor));
        mLockHeadView.setVisibility(View.VISIBLE);

        mTableScrollView.setHorizontalFadingEdgeEnabled(false);
        creatHeadView();
        createLockColumnView();
    }

    /**
     * 创建头部视图
     */
    private void creatHeadView() {

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mLeftTopView.getLayoutParams();
        layoutParams.width = DisplayUtil.dip2px(mContext, tableWithAndHeight);
        layoutParams.height = DisplayUtil.dip2px(mContext, tableWithAndHeight);
//        layoutParams.setMargins(70, 70, 70, 70);
        mLeftTopView.setLayoutParams(layoutParams);
        //构造滚动视图
        createScollview(mLockScrollView, mTableFristTitleData, true);
        mScrollViews.add(mLockScrollView);
        mLockScrollView.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
            @Override
            public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                changeAllScrollView(x, y);
            }
        });
    }


    /**
     * 创建锁定列视图
     */
    private void createLockColumnView() {
        View lockTableViewContent = LayoutInflater.from(mContext).inflate(R.layout.locktablecontentview, null);
        LinearLayout lockViewParent = (LinearLayout) lockTableViewContent.findViewById(R.id.lockView_parent);
        CustomHorizontalScrollView lockScrollViewParent = (CustomHorizontalScrollView) lockTableViewContent.findViewById(R.id.lockScrollView_parent);
        //构造锁定视图
        for (int i = 0; i < mTableBallPersonDatas.size(); i++) {
            //构造TextView容器，如果要设置背景色设置这一个而不是设置TextView，TextView有外边距设置不全
            LinearLayout textViewContainer = new LinearLayout(mContext);
            LinearLayout.LayoutParams textLinearParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            textViewContainer.setOrientation(LinearLayout.HORIZONTAL);
            textViewContainer.setLayoutParams(textLinearParams);


            //构造View
            View columnView = mTableAdapter.getColumnView(i, mTableBallPersonDatas.get(i));

            //设置布局
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
//            textViewParams.setMargins(70, 70, 70, 25);
            columnView.setLayoutParams(textViewParams);


            ViewGroup.LayoutParams layoutParams = columnView.getLayoutParams();
            layoutParams.width = DisplayUtil.dip2px(mContext, tableWithAndHeight);
            layoutParams.height = DisplayUtil.dip2px(mContext, tableWithAndHeight);
            columnView.setLayoutParams(layoutParams);


            textViewContainer.addView(columnView);
            //表格线
            View splite = new View(mContext);
            ViewGroup.LayoutParams spliteLayoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    DisplayUtil.dip2px(mContext, 1));
            splite.setLayoutParams(spliteLayoutParam);
            splite.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
            lockViewParent.addView(textViewContainer);
            lockViewParent.addView(splite);
        }
        //构造滚动视图
        LinearLayout scollViewItemContentView = new LinearLayout(mContext);
        LinearLayout.LayoutParams scollViewItemContentViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        scollViewItemContentView.setLayoutParams(scollViewItemContentViewParams);
        scollViewItemContentView.setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < mTableRowDatas.size(); i++) {
            ArrayList<TableData> datas = mTableRowDatas.get(i);
            //设置LinearLayout
            LinearLayout linearLayout = new LinearLayout(mContext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < datas.size(); j++) {
                //构造单元格
                View tableView = mTableAdapter.getTableView(i, j, datas.get(j));

                //设置布局
                LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
//                textViewParams.setMargins(70, 70, 70, 25);
                textViewParams.height = DisplayUtil.dip2px(mContext, tableWithAndHeight);
                tableView.setLayoutParams(textViewParams);
                ViewGroup.LayoutParams textViewParamsCopy = tableView.getLayoutParams();
                textViewParamsCopy.width = DisplayUtil.dip2px(mContext, tableWithAndHeight);
                /**-----------------------------start-------------------------------------*/

                final int finalJ = j;
                final int finalI = i;
                tableView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mClickItemListener.onClickListener(finalI, finalJ);
                    }
                });
                /**-----------------------------end-------------------------------------*/
                linearLayout.addView(tableView);
                //右侧分隔线
                if (j != datas.size() - 1) {
                    View splitView = new View(mContext);
                    ViewGroup.LayoutParams splitViewParmas = new ViewGroup.LayoutParams(DisplayUtil.dip2px(mContext, 1),
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    splitView.setLayoutParams(splitViewParmas);
                    splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                    linearLayout.addView(splitView);
                }
            }
            scollViewItemContentView.addView(linearLayout);
            //底部分隔线
            View splite = new View(mContext);
            ViewGroup.LayoutParams spliteLayoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    DisplayUtil.dip2px(mContext, 1));
            splite.setLayoutParams(spliteLayoutParam);
            splite.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
            scollViewItemContentView.addView(splite);
        }
        lockScrollViewParent.addView(scollViewItemContentView);
        mScrollViews.add(lockScrollViewParent);
        lockScrollViewParent.setOnScrollChangeListener(new CustomHorizontalScrollView.onScrollChangeListener() {
            @Override
            public void onScrollChanged(HorizontalScrollView scrollView, int x, int y) {
                changeAllScrollView(x, y);
            }
        });
        mTableScrollView.addView(lockTableViewContent);
    }


    /**
     * 改变所有滚动视图位置
     *
     * @param x
     * @param y
     */
    private void changeAllScrollView(int x, int y) {
        if (mScrollViews.size() > 0) {
            if (mTableViewListener != null) {
                mTableViewListener.onTableViewScrollChange(x, y);
            }
            for (int i = 0; i < mScrollViews.size(); i++) {
                HorizontalScrollView scrollView = mScrollViews.get(i);
                scrollView.scrollTo(x, y);
            }
        }
    }


    /**
     * 构造滚动视图
     *
     * @param scrollView
     * @param datas
     * @param isFristRow 是否是第一行
     */
    private void createScollview(HorizontalScrollView scrollView, List<TitleData> datas, boolean isFristRow) {
        //设置LinearLayout
        LinearLayout linearLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        for (int i = 0; i < datas.size(); i++) {
            //构造单元格
            View titleView = mTableAdapter.getTitleView(i, datas.get(i));

            //设置布局
            LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
//            textViewParams.setMargins(70, 0, 70, 0);
            titleView.setLayoutParams(textViewParams);
            ViewGroup.LayoutParams textViewParamsCopy = titleView.getLayoutParams();
            textViewParamsCopy.width = DisplayUtil.dip2px(mContext, tableWithAndHeight);
            textViewParamsCopy.height = DisplayUtil.dip2px(mContext, tableWithAndHeight);
            linearLayout.addView(titleView);
            //画分隔线
            if (i != datas.size() - 1) {
                View splitView = new View(mContext);
                ViewGroup.LayoutParams splitViewParmas = new ViewGroup.LayoutParams(DisplayUtil.dip2px(mContext, 1),
                        ViewGroup.LayoutParams.MATCH_PARENT);
                splitView.setLayoutParams(splitViewParmas);
                if (isFristRow) {
                    splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                } else {
                    splitView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.light_gray));
                }
                linearLayout.addView(splitView);
            }
        }
        scrollView.addView(linearLayout);
    }


    public LockTableView setMaxColumnWidth(int maxColumnWidth) {
        this.maxColumnWidth = maxColumnWidth;
        return this;
    }

    public LockTableView setMinColumnWidth(int minColumnWidth) {
        this.minColumnWidth = minColumnWidth;
        return this;
    }

    public LockTableView setFristRowBackGroudColor(int mFristRowBackGroudColor) {
        this.mFristRowBackGroudColor = mFristRowBackGroudColor;
        return this;
    }

    public LockTableView setNullableString(String mNullableString) {
        this.mNullableString = mNullableString;
        return this;
    }

    public LockTableView setTextViewSize(int mTextViewSize) {
        this.mTextViewSize = mTextViewSize;
        return this;
    }

    public LockTableView setTableHeadTextColor(int mTableHeadTextColor) {
        this.mTableHeadTextColor = mTableHeadTextColor;
        return this;
    }

    public LockTableView setTableContentTextColor(int mTableContentTextColor) {
        this.mTableContentTextColor = mTableContentTextColor;
        return this;
    }

    public LockTableView setMaxRowHeight(int maxRowHeight) {
        this.maxRowHeight = maxRowHeight;
        return this;
    }

    public LockTableView setMinRowHeight(int minRowHeight) {
        this.minRowHeight = minRowHeight;
        return this;
    }

    public LinearLayout getLeftTopView() {
        return mLeftTopView;
    }

    public LockTableView setTableViewListener(OnTableViewListener mTableViewListener) {
        this.mTableViewListener = mTableViewListener;
        return this;
    }

    //值获取
    public ArrayList<Integer> getColumnMaxWidths() {
        return mColumnMaxWidths;
    }

    public ArrayList<Integer> getRowMaxHeights() {
        return mRowMaxHeights;
    }

    public LinearLayout getLockHeadView() {
        return mLockHeadView;
    }


    public ArrayList<HorizontalScrollView> getScrollViews() {
        return mScrollViews;
    }

    //回调监听
    public interface OnTableViewListener {
        /**
         * 滚动监听
         *
         * @param x
         * @param y
         */
        void onTableViewScrollChange(int x, int y);
    }

    //点击事件监听
    public interface onClickItemListener {
        /**
         * 点击事件
         *
         * @param i 行
         * @param j 列
         */
        void onClickListener(int i, int j);
    }

    public LockTableView setOnClickListener(onClickItemListener listener) {
        this.mClickItemListener = listener;
        return this;
    }



    public LockTableView setAdapter(TableAdapter adapter) {
        this.mTableAdapter = adapter;
        adapter.setTableView(this);
        mTableFristTitleData = adapter.mTableFristTitleData;
        mTableBallPersonDatas = adapter.mTableBallPersonDatas;
        mTableRowDatas = adapter.mTableRowDatas;
        return this;
    }

}
